;
; Written for Andrew on GimpTalk
;  see http://www.gimptalk.com/index.php?/topic/58881-counting-objects-in-a-pho/
;
(define selffilename "\n- andrew_count_dots.scm")

; this routine is used to count the number of dots of a certain colour on a specified layer
(define (andrew_count_dots image unused_drawable drawable dot_colour leave_selection)                     
  (let* (
          (number_of_dots 0)                 ; variable to hold the number of dots found
          (vectors 0)                        ; variable to hold the vectors
        )
        (gimp-image-undo-group-start image)
        (gimp-message-set-handler ERROR-CONSOLE)             ; force gimp-message to use the error console
        (gimp-by-color-select drawable dot_colour 0 CHANNEL-OP-REPLACE TRUE FALSE 0 FALSE) ; select everything on the layer that's the wanted colour
        (if (= (car (gimp-selection-is-empty image)) TRUE)   ; nothing found
          (begin
            (gimp-image-undo-group-end image)
            (error "There are no dots")
          )
        )
        (plug-in-sel2path RUN-NONINTERACTIVE image drawable)           ; turn the selection into paths
        (set! vectors (car (gimp-image-get-active-vectors image)))     ; get the list of vectors
        (set! number_of_dots (car (gimp-vectors-get-strokes vectors))) ; get the number of strokes that make up the vectors
        (gimp-image-remove-vectors image vectors)                      ; delete the paths as we don't need them anymore
        (if (= leave_selection FALSE)
          (gimp-selection-none image)                                  ; de-select everything
        )
        (gimp-message (string-append "There are " (number->string number_of_dots) " dots"))  
        (gimp-displays-flush)
        (gimp-image-undo-group-end image)
  )
)

; define the user interface
(script-fu-register "andrew_count_dots"
		    _"Count the dots..."
		    (string-append "Count the number of dots on a layer" selffilename)
		    "I did this"
		    "GPL License"
		    "12/09/2013"
		    "*"
		    SF-IMAGE "Input Image" 0
		    SF-DRAWABLE "Drawable" 0
		    SF-LAYER "Dots layer" 0
                    SF-COLOR  _"Dot Colour" '(0 0 0)
                    SF-TOGGLE _"Leave Selection?" FALSE
)

; where the menu entry goes
(script-fu-menu-register "andrew_count_dots" "<Image>/contributed")
